//
//  ComposeViewController.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/10.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    // MARK: - Property
    /* 微博文本 */
    @IBOutlet weak var statusTextView: ComposeTextView!
    /* 微博发送按钮 */
    @IBOutlet weak var sendButton: UIBarButtonItem!
    /* 底部工具栏底部约束 */
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    /* 剩余文字提醒 */
    @IBOutlet weak var tipLabel: UILabel!
    /* 文字最大输入数 */
    let maxCount = 140
    /* 容器视图高度 */
    @IBOutlet weak var containerViewHeightCons: NSLayoutConstraint!
    /* 图片选取控制器 */
    var photoPickerVC: PhotoPickerViewController?
    
    // MARK: - Lazy
    private lazy var keyboardEmoticonVC: KeyboardEmoticonViewController = KeyboardEmoticonViewController { [unowned self] (emoticon) in
        /* 插入表情 */
        self.statusTextView.insertEmoticon(emoticon)
        /* 主动调用 */
        self.textViewDidChange(self.statusTextView)
    }
    
    // MARK: - Life
    override func viewDidLoad() {
        super.viewDidLoad()
        /* 注册通知，监听键盘变化 */
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewController.keyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        /* 添加表情键盘控制器 */
        addChildViewController(keyboardEmoticonVC)
        /* 容器视图先不显示 */
        containerViewHeightCons.constant = 0
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        if containerViewHeightCons.constant == 0 {
            statusTextView.becomeFirstResponder()
        }
    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(true)
        statusTextView.resignFirstResponder()
    }
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    /* 获取图片选择控制器 */
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "photoPickerSegue" {
            photoPickerVC = segue.destinationViewController as? PhotoPickerViewController
        }
    }

    // MARK: - 内部控制方法
    @objc private func keyboardWillChange(notice: NSNotification) {
        // UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 568}, {320, 253}}";
        let rect = notice.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        let height = UIScreen.mainScreen().bounds.height
        let offsetY = height - rect.origin.y
        /* 解决键盘跳动：设置动画节奏为7 */
        let curve = notice.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        
        toolbarBottomCons.constant = offsetY
        UIView.animateWithDuration(0.25) {
            /* 设置动画节奏 */
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue:curve.integerValue)!)
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - Event
    @IBAction func closeButtonClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @IBAction func sendButtonClick() {
        // TODO: - Continue
        /* 新浪开发者API接口默认只可以上传一张图片 */
        let image = photoPickerVC?.images.first
        /* 微博内容 */
        let statusText = statusTextView.getEmoticonStr()
        /* 发送微博提醒 */
        SVProgressHUD.showInfoWithStatus("正在发送微博")
        /* 发送微博 */
        NetworkTools.shareInstance.sendStatus(statusText, image: image) { (dict, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送微博失败")
                return
            }
            if dict != nil {
                SVProgressHUD.showSuccessWithStatus("发送微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    @IBAction func pictureBarBtnClick(sender: AnyObject) {
        /* 控制容器视图显示 */
        containerViewHeightCons.constant = UIScreen.mainScreen().bounds.height * 0.65
        UIView.animateWithDuration(0.4) { 
            self.view.layoutIfNeeded()
        }
        statusTextView.resignFirstResponder()
    }

    @IBAction func emotionBarBtnClick(sender: AnyObject) {
        /* 需先关闭键盘 */
        statusTextView.resignFirstResponder()
        /* 判断后切换键盘 */
        if statusTextView.inputView == nil { // 切换成表情键盘
            statusTextView.inputView = keyboardEmoticonVC.view
        } else { // 表情键盘
            statusTextView.inputView = nil
        }
        /* 开启键盘 */
        statusTextView.becomeFirstResponder()
    }
}

// MARK: - Delegate
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        /* 当有内容时发送按钮可点击 */
        sendButton.enabled = textView.hasText()
        /* 控制占位字符的隐藏 */
        self.statusTextView.placeholderLabel.hidden = textView.hasText()
        
        /* 剩余文字提醒及相关设置 */
        let currentCount = statusTextView.getEmoticonStr().characters.count
        let leftCount = maxCount - currentCount
        tipLabel.text = "可输入\(leftCount)字符"
        sendButton.enabled = (leftCount >= 0)
        tipLabel.textColor = (leftCount > 0) ? UIColor.lightGrayColor() : UIColor.redColor()
    }
    
}
